package cn.hxh.page.controller;

import cn.hxh.page.pojo.Config;
import cn.hxh.page.pojo.User;
import cn.hxh.page.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: HongXiaoHan
 * @Description
 * @Date: 2020/10/5 16:58
 */

//用户控制器
@Controller
public class UserController {

    @Autowired
    private UserService service;

    //验证seesion是否存在
    @ResponseBody
    @RequestMapping("/user/session")
    public User verifySession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User userSession = (User) session.getAttribute(Config.USER_INFO);
        return userSession;
    }

    @ResponseBody
    @RequestMapping("/user/login")
    public User login(HttpServletRequest request,
                      @RequestParam("password")String password,
                      @RequestParam("account")String account) {
        //调用service
        User user = service.login(password, account);
        if (user != null){
            HttpSession session = request.getSession();
            session.setAttribute(Config.USER_INFO,user);
        }
        return user;
    }

    @ResponseBody
    @RequestMapping("/user/register")
    public int register(@RequestParam("password")String password,
                         @RequestParam("account")String account) {
        //调用service
        int flag = service.register(password,account);

        return flag;
    }



    @ResponseBody
    @RequestMapping("/user/loginOut")
    public int loginOut(HttpServletRequest request) {
        int flag = 0;
        try {
            HttpSession session = request.getSession();
            session.invalidate();
            flag = 1;
        }catch (Exception e){
            flag = 0;
            System.out.println("注销失败");
        }
        return flag;
    }

}
